<?php

namespace App\Http\Controllers\Home;

use App\Model\Branch;
use App\Model\BranchTest;
use App\Model\Goods;
use App\Model\Order;
use App\Model\Order1;
use App\Model\PushOrder;
use App\Model\tel;
use App\Model\User;
use App\Model\UserBranchTest;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class BranchController extends Controller
{
    //正式
    private $url = "http://openapi.fulu.com/api/getway";
    private $app_key = "YZ2Fu5Y86kfnF4qIcKCtOK9PjJzlv4w7kq+bPPu0SmeZxjqn5gUBgTAthCnxFOXP";
    private $app_secret = "10888069844749068c5f6fe742796e0b";

    //商户管理--订单列表
    public function order(Request $request){
        $user = session('user');
        $role_id = (new UserBranchTest) -> getRoleId($user['id']);
        if($user['id'] == 1 || $user['id'] == 3){
            $order = Order::orderBy("id","desc")->where(function($query) use($request){
                $orderno =$request->input('orderno');
                $account = $request->input('account');
                if($orderno){
                    $query->where('orderno','like','%'.$orderno.'%');
                }
                if($account){
                    $query->where('chargeaccount','like','%'.$account.'%');
                }
            })->paginate($request->input("num")?$request->input("num"):20);

            foreach ($order as $k=>$v){
                preg_match('/\d+/',$v['productname'],$price);
                $order[$k]['remainingnumber'] = $price[0];
            }
        }elseif ($user['id'] == 7){
            $between = [0,14];
            $str_time = User::where('id',$user['id']) ->select('created_at')->first();
            $time = strtotime($str_time);
            $order = Order::orderBy("id","desc")->where(function($query) use($request){
                $orderno =$request->input('orderno');
                $account = $request->input('account');
                if($orderno){
                    $query->where('orderno','like','%'.$orderno.'%');
                }
                if($account){
                    $query->where('chargeaccount','like','%'.$account.'%');
                }
            })->where('buytime','>',$time)->whereBetween('bid',$between)->paginate(20);
        } else{
            $order = tel::orderBy("id","desc")->where(function($query) use($request){
                $orderno =$request->input('orderno');
                $account = $request->input('account');
                if($orderno){
                    $query->where('orderno','like','%'.$orderno.'%');
                }
                if($account){
                    $query->where('chargeaccount','like','%'.$account.'%');
                }
            })->where('bid',$role_id)->paginate($request->input("num")?$request->input("num"):20);

            foreach ($order as $k=>$v){
                if($v['isok'] == 1){
                    $order[$k]['status'] = "充值成功";
                }elseif ($v['isok'] == 2){
                    $order[$k]['status'] = "充值失败";
                }else{
                    $order[$k]['status'] = "正在处理";
                }
            }

        }

//        return view("home.branch.order",compact("order","request","count_today",'count','count_false','count_today_false'));
        return view("home.branch.order",compact("order","request"));
    }


    //商户管理--商品列表
    public function goods(Request $request){
        $goods = Goods::get();
        return view("home.branch.goods",compact("goods"));
    }

    // 列表页
    public function index(Request $request)
    {
        $today = strtotime(date("Y-m-d",time()));

        $branch = Branch::orderBy("id","desc")->where(function($query) use($request){
            $username =$request->input('username');
            $tel =$request->input('tel');
            if($username){
                $query->where('username','like','%'.$username.'%');
            }
            if($tel){
                $query->where('tel','like','%'.$tel.'%');
            }
        })->paginate($request->input("num")?$request->input("num"):10);
        foreach ($branch as $k=>$v){
            $branch[$k]['today'] = Order::where("time","<",$today)->where('bid',$v['id'])->where("isok",1)->avg("oktime");
            $branch[$k]['all'] = Order::where('bid',$v['id'])->where("isok",1)->avg("oktime");
        }
        return view("home.branch.list",compact("branch","request"));
    }

    //下游获取订单信息
    public function getOrder(Request $request){
        $data = $request->post();
        $branch = Branch::where("userkey",$data['userKey'])->first();
        if($branch['tel'] == 1){
            if(isset($data['userKey']) && isset($data['userSecret'])){
                $userKey = $data['userKey'];
                $branch = Branch::where("userkey",$userKey)->first();
                if($branch){
                    if($branch['usersecret'] === $data['userSecret']){
                        if(isset($data['productPrice'])){
                            $res = DB::select("select id,buytime,chargeaccount,remainingnumber,url,num,orderno from tiktok_pushorder where status = '未处理' AND chargetype = 2 AND remainingnumber = ".$data['productPrice']." order by id asc limit 1");
                        }else{
                            $res = DB::select("select id,buytime,chargeaccount,remainingnumber,url,num,orderno from tiktok_pushorder where status = '未处理' AND chargetype = 2 order by id asc limit 1");
                        }
                        if(isset($res[0])){
                            $res = $res[0];
                            $num = Branch::where("tel",1)->count();
                            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                            if($res->id % $num == 0){
                                $info['bid'] = $branch['id'];
                                $info['status'] = "已处理";
                                $info['branch'] = '已被获取，等回调';
                                $info['isok'] = 3;
                                $info['time'] = time();
                                Order::where("orderno",$res->orderno)->update($info);
                                PushOrder::where("id",$res->id)->update($info);
                                $order['num'] = $branch['num'] + 1;
//                        $order['money'] = $branch['money'] + $res->productprice;
                                if($branch['ip'] == ''){
                                    $order['ip'] = $_SERVER['REMOTE_ADDR'];
                                }
                                Branch::where("id",$branch['id'])->update($order);
                                return json_encode([
                                    "status"=>1,
                                    "msg"=>"success",
                                    "data"=>[
                                        "buyTime"=>$res->buytime,
                                        "productPrice"=>$res->remainingnumber * $res->num,
                                        "chargeAccount"=>$res->chargeaccount,
                                        "url"=>$res->url,
                                        "orderNo"=>$res->orderno
                                    ]
                                ]);
                            }
                        }else{
//                            return json_encode([
//                                "status"=>2,
//                                "msg"=>"error",
//                                "data"=>"没有对应金额订单"
//                            ],JSON_UNESCAPED_UNICODE);
                        }
                    }else{
                        return json_encode([
                            "status"=>0,
                            "msg"=>"userSecret值错误"
                        ],JSON_UNESCAPED_UNICODE);
                    }
                }else{
                    return json_encode([
                        "status"=>0,
                        "msg"=>"userKey值错误"
                    ],JSON_UNESCAPED_UNICODE);
                }
            }else{
                return json_encode([
                    "status"=>0,
                    "msg"=>"缺少必要的参数"
                ],JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode([
                "status"=>0,
                "msg"=>"已停止推单"
            ],JSON_UNESCAPED_UNICODE);
        }

    }


    public function getTestOrder(Request $request){
        $data = $request->post();
        $branch = BranchTest::where("userkey",$data['userKey'])->first();
        if($branch['tel'] == 1){
            if(isset($data['userKey']) && isset($data['userSecret'])){
                $userKey = $data['userKey'];
                $branch = BranchTest::where("userkey",$userKey)->first();
                if($branch){
                    if($branch['usersecret'] === $data['userSecret']){
                        if(isset($data['productPrice'])){
                            $res = DB::select("select id,buytime,chargeaccount,remainingnumber,orderno from tiktok_order1 where status = '未处理' AND chargetype = 2 AND remainingnumber = ".$data['productPrice']." order by id asc limit 1");
                        }else{
                            $res = DB::select("select id,buytime,chargeaccount,remainingnumber,orderno from tiktok_order1 where status = '未处理' AND chargetype = 2 order by id asc limit 1");
                        }
                        if($res){
                            $res = $res[0];
                            $info['bid'] = $branch['id'];
                            $info['status'] = "已处理";
                            $info['branch'] = '已被获取，等回调';
                            $info['time'] = time();
                            Order1::where("id",$res->id)->update($info);
                            $order['ip'] = $_SERVER['REMOTE_ADDR'];
                            BranchTest::where("id",$branch['id'])->update($order);
                            return json_encode([
                                "status"=>1,
                                "msg"=>"success",
                                "data"=>[
                                    "buyTime"=>$res->buytime,
                                    "productPrice"=>$res->remainingnumber,
                                    "chargeAccount"=>$res->chargeaccount,
                                    "orderNo"=>$res->orderno
                                ]
                            ]);
                        }else{
                            return json_encode([
                                "status"=>2,
                                "msg"=>"error",
                                "data"=>"没有对应金额订单"
                            ]);
                        }
                    }else{
                        return json_encode([
                            "status"=>0,
                            "msg"=>"userSecret值错误"
                        ]);
                    }
                }else{
                    return json_encode([
                        "status"=>0,
                        "msg"=>"userKey值错误"
                    ]);
                }
            }else{
                return json_encode([
                    "status"=>0,
                    "msg"=>"缺少必要的参数"
                ]);
            }
        }else{
            return json_encode([
                "status"=>0,
                "msg"=>"已停止推单"
            ]);
        }
    }

    //下游确认订单信息
    public function orderStatus(Request $request){
        $data = $request->post();
        if(isset($data['userKey']) && isset($data['userSecret']) && isset($data['status']) && isset($data['orderNo']) ){
            $userKey = $data['userKey'];
            $branch = Branch::where("userkey",$userKey)->first();
            if($branch){
                if($branch['usersecret'] === $data['userSecret']){
                    $orderInfo = Order::where('orderno',$data['orderNo']) ->first();
                    if($orderInfo['isok'] == 3){
                        if($data['status'] == 1 || $data['status'] == 2){
                            $info['isok'] = $data['status'];
                            $info['time'] = time();
                            if($data['status'] == 1){
                                $info['branch'] = "充值成功";
                                $order['money'] = $branch['money'] + $orderInfo->remainingnumber;
                                $order['successmoney'] = $branch['successmoney'] + $orderInfo->remainingnumber;
                                $order['successnum'] = $branch['successnum'] + 1;
                                Branch::where("userkey",$userKey)->update($order);
//                                $this->callBackOrderStatus($orderInfo['orderno'],$data['status'],time());
                                $infoFulu['branch'] = '充值成功';
                                $infoFulu['status'] = '已处理';
                                $infoFulu['isok'] = 1;
                                $infoFulu['bid'] = $branch['id'];
                                PushOrder::where('orderno', $orderInfo['orderno'])->update($infoFulu);
                                Order::where('orderno', $orderInfo['orderno'])->update($infoFulu);
                                $this->callBackOrderStatus($orderInfo['orderno'],1,time());
                            }else{
                                /*直接失败*/
                                $info['branch'] = "充值失败";
                                $order['money'] = $branch['money'] + $orderInfo->remainingnumber;
                                Branch::where("userkey",$userKey)->update($order);
                                $this->callBackOrderStatus($orderInfo['orderno'],2,time());
                                $infoFulu['branch'] = '充值失败';
                                $infoFulu['status'] = '已处理';
                                $infoFulu['isok'] = 2;
                                $infoFulu['bid'] = $branch['id'];
                                PushOrder::where('orderno', $data['orderNo'])->update($infoFulu);
                                Order::where('orderno', $data['orderNo'])->update($infoFulu);
                                /*直接失败*/
                                /*福禄直充*/
//                                $order = PushOrder::where('orderno',$data['orderNo'])->first();
//                                switch ($order['remainingnumber']){
//                                    case 100:
//                                        $product_id = 10707887;
//                                        break;
//                                    case 200:
//                                        $product_id = 19016689;
//                                        break;
//                                    case 300:
//                                        $product_id = 19016698;
//                                        break;
//                                    case 500:
//                                        $product_id = 19016699;
//                                        break;
//                                    case 1000:
//                                        $product_id = 19016700;
//                                        break;
//                                }
//                                $resFulu = $this->pushOrderFulu($product_id,$order['orderno'],$order['chargeaccount']);
//                                if($resFulu->code == 0){
//                                    $infoFulu['branch'] = '已推送快充';
//                                    $infoFulu['status'] = '已处理';
//                                    $infoFulu['isok'] = 4;
//                                    $infoFulu['bid'] = 888;
//                                    Order::where('orderno', $order['orderno'])->update($infoFulu);
//                                    PushOrder::where('orderno', $order['orderno'])->update($infoFulu);
//                                }else{
//                                    $infoFulu['branch'] = $resFulu->code;
//                                    $infoFulu['status'] = '查询福禄失败原因';
//                                    $infoFulu['isok'] = 4;
//                                    $infoFulu['bid'] = 0;
//                                    Order::where('orderno', $order['orderno'])->update($infoFulu);
//                                    PushOrder::where('orderno', $order['orderno'])->update($infoFulu);
//                                }
                            }
                            echo json_encode([
                                "status"=>1,
                                "msg"=>"success"
                            ],JSON_UNESCAPED_UNICODE);
                        }else{
                            return json_encode([
                                "status"=>0,
                                "msg"=>"status值为1成功，为2失败，其它值不通过"
                            ],JSON_UNESCAPED_UNICODE);
                        }
                        $info['oktime'] = time() - $orderInfo['time'];
                        Order::where('orderno',$data['orderNo']) ->update($info);
//                        $this->callBackOrderStatus($orderInfo['orderno'],$data['status'],time());
                    }else{
                        return json_encode([
                            "status"=>0,
                            "msg"=>"无需重复提交"
                        ],JSON_UNESCAPED_UNICODE);
                    }
                }else{
                    return json_encode([
                        "status"=>0,
                        "msg"=>"userSecret值错误"
                    ],JSON_UNESCAPED_UNICODE);
                }
            }else{
                return json_encode([
                    "status"=>0,
                    "msg"=>"userKey值错误"
                ],JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode([
                "status"=>0,
                "msg"=>"缺少必要的参数"
            ],JSON_UNESCAPED_UNICODE);
        }
    }

    //下单到福禄
    public function pushOrderFulu($product_id,$customer_order_no,$charge_account,$buy_num = 1){
//    public function pushOrderFulu(){
        $param = [
            "product_id"    =>  $product_id,
            "customer_order_no"    =>  $customer_order_no,
            "charge_account"    =>  $charge_account,
            "buy_num"    =>  $buy_num
        ];

//        $param = [
//            "product_id"    =>  19011238,
//            "customer_order_no"    =>  "201906281030191013526",
//            "charge_account"    =>  "888888",
//            "buy_num"    =>  1
//        ];

        $data = [
            "app_key"   =>  $this->app_key,
            "method"    =>  "fulu.order.direct.add",
            "timestamp" =>  date("Y-m-d H:i:s",time()),
            "version"   =>  "2.0",
            "format"    =>  "json",
            "charset"    =>  "utf-8",
            "sign_type"    =>  "md5",
            "app_auth_token"    =>  "",
            "biz_content"    =>  json_encode($param),
        ];
        $sign = $this->getSign($data);

        $data['sign'] = $sign;

//        echo "<pre>";
//        var_dump($data);
//        echo "<br>";

        $res = $this->curlFulu($this->url,json_encode($data,JSON_UNESCAPED_SLASHES));

        $res = json_decode($res);

        return $res;

    }

    public function getSign($Parameters){
        //签名步骤一：把字典json序列化
        $json = json_encode( $Parameters, JSON_UNESCAPED_SLASHES);
        //签名步骤二：转化为数组
        $jsonArr = $this->mb_str_split( $json );
        //签名步骤三：排序
        sort( $jsonArr );
        //签名步骤四：转化为字符串
        $string = implode( '', $jsonArr );
        //签名步骤五：在string后加入secret
        $string = $string . $this->app_secret;
        //签名步骤六：MD5加密
        $result_ = strtolower( md5( $string ) );
        return $result_;
    }

    function mb_str_split($str){
        return preg_split('/(?<!^)(?!$)/u', $str );
    }

    public function curlFulu($url,$post_data = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    //下游测试确认订单信息
    public function orderStatusTest(Request $request){
        $method = $request->getMethod();
        if($method=='get'){
            return "访问方式不正确，请用POST访问";
        }
        $data = $request->post();
        if(isset($data['userKey']) && isset($data['userSecret']) && isset($data['status']) && isset($data['orderNo']) ){
            $userKey = $data['userKey'];
            $branch = BranchTest::where("userkey",$userKey)->first();
            if($branch){
                if($branch['usersecret'] === $data['userSecret']){
                    $orderInfo = Order1::where('orderno',$data['orderNo']) ->first();
                    if($data['status'] == 1 || $data['status'] == 2){
                        $info['isok'] = $data['status'];
                        $info['oktime'] = time() - $orderInfo['time'];
                        if($data['status'] == 1){
                            $info['branch'] = "充值成功";
                            Order1::where('orderno',$data['orderNo']) ->update($info);
                        }else{
                            $info['branch'] = "充值失败";
                            Order1::where('orderno',$data['orderNo']) ->update($info);
                        }
                        echo json_encode([
                            "status"=>1,
                            "msg"=>"success"
                        ]);
                    }else{
                        return json_encode([
                            "status"=>0,
                            "msg"=>"status值为1成功，为2失败，其它值不通过"
                        ]);
                    }
//                    $this->callBackOrderStatus($orderInfo['orderno'],$data['status'],time());
                }else{
                    return json_encode([
                        "status"=>0,
                        "msg"=>"userSecret值错误"
                    ]);
                }
            }else{
                return json_encode([
                    "status"=>0,
                    "msg"=>"userKey值错误"
                ]);
            }
        }else{
            return json_encode([
                "status"=>0,
                "msg"=>"缺少必要的参数"
            ]);
        }
    }

//上游订单确认
//反状态（OrderId：订单号（同取单接口fuluOrderId），OrderStatus：订单状态（1：成功 2：失败），ChargeResult：充值描述，RealCost：成本（外部可随意），amount_type：固定RMB，SubstituteAccount：固定“外部商户”，ChannelAccountId：固定“外部商户”）
    function callBackOrderStatus($orderId,$orderStatus,$time,$str='Serge#57$768rtv0'){

        $sign = strtoupper(md5($orderId.$orderStatus.$time.$str));

        if($orderStatus == 1){
            $postData = "OrderId=".$orderId."&OrderStatus=".$orderStatus."&Description=充值成功&RealCost=0&Currency=RMB&SubstituteAccount=外部商户042&ChannelAccountId=外部商户042&Ts=".$time."&Sign=".$sign;
        }else{
            $postData = "OrderId=".$orderId."&OrderStatus=".$orderStatus."&Description=充值失败&RealCost=0&Currency=RMB&SubstituteAccount=外部商户042&ChannelAccountId=外部商户042&Ts=".$time."&Sign=".$sign;
        }


        $url = "http://interface.qsios.cn:8136/actionapi/Order/CallBackOrderStatus";

        $res = $this->curlPost($url,$postData);

        return $res;
    }

//手动传回失败订单
    function orderError(Request $request){
        $id = $request->input('id');
        $orderInfo = Order::where("id",$id)->first();
        //失败
        if($orderInfo){
            $time = time();
            $res = $this->callBackOrderStatus($orderInfo['orderno'],2,$time);
            if(isset($res)){
                $info['isok'] = 2;
                $info['status'] = '已处理';
                $info['branch'] = '充值失败';
                $info['oktime'] = $time - $orderInfo['buytime'];
                Order::where('id',$id)->update($info);
                PushOrder::where('orderno',$orderInfo['orderno'])->update($info);
            }
            return $res;
        }
    }

    //手动传回失败订单
//    function orderError(Request $request){
//        $id = $request->input('id');
//        $orderInfo = Order::where("id",$id)->first();
//        $order = PushOrder::where('orderno',$orderInfo['orderno'])->first();
//        switch ($order['remainingnumber']){
//            case 100:
//                $product_id = 10707887;
//                break;
//            case 200:
//                $product_id = 19016689;
//                break;
//            case 300:
//                $product_id = 19016698;
//                break;
//            case 500:
//                $product_id = 19016699;
//                break;
//            case 1000:
//                $product_id = 19016700;
//                break;
//        }
//        $resFulu = $this->pushOrderFulu($product_id,$order['orderno'],$order['chargeaccount']);
//        if($resFulu->code == 0){
//            $infoFulu['branch'] = '已推送快充';
//            $infoFulu['status'] = '已处理';
//            $infoFulu['isok'] = 4;
//            $infoFulu['bid'] = 888;
//            Order::where('orderno', $order['orderno'])->update($infoFulu);
//            PushOrder::where('orderno', $order['orderno'])->update($infoFulu);
//        }else{
//            $infoFulu['branch'] = $resFulu->code;
//            $infoFulu['status'] = '查询福禄失败原因';
//            $infoFulu['isok'] = 4;
//            $infoFulu['bid'] = 0;
//            Order::where('orderno', $order['orderno'])->update($infoFulu);
//            PushOrder::where('orderno', $order['orderno'])->update($infoFulu);
//        }
//    }

//手动传回成功订单
    function orderSuccess(Request $request){
        $id = $request->input('id');
        $orderInfo = Order::where("id",$id)->first();
        //失败
        if($orderInfo){
            $time = time();
            $res = $this->callBackOrderStatus($orderInfo['orderno'],1,$time);
            if(isset($res)){
                $info['isok'] = 1;
                $info['status'] = '已处理';
                $info['branch'] = '充值成功';
                Order::where('id',$id)->update($info);
            }
            return $res;
        }
    }

    //用户添加页面
    public function create()
    {
        return view("home.branch.add");
    }

    public function show($id){

    }

    //添加操作
    public function store(Request $request)
    {
        $user = $request->post();

        $user['usersecret'] = md5($user['userkey'].'whosyourdaddy');
        $user['tel'] = 2;
        $res = Branch::create($user);
        BranchTest::create($user);
        if($res){
            echo json_encode([
                "code"=>1,
                "msg"=>"success"
            ]);
        }else{
            echo json_encode([
                "code"=>0,
                "msg"=>"error"
            ]);
        }
    }

    //返回修改页面
    public function edit($id)
    {
        $branch = Branch::find($id);
        return view("home.branch.edit",compact('branch'));
    }

    //执行修改操作
    public function update(Request $request, $id)
    {
        $branch = $request -> all();
        if($request->input('userkey')){
            $branch['usersecret'] = md5($branch['userkey'].'whosyourdaddy');
        }
        unset($branch['s']);
        $res = Branch::where("id",$id)->update($branch);
        if($res){
            echo json_encode([
                "code"=>1,
                "msg"=>"success"
            ]);
        }else{
            echo json_encode([
                "code"=>0,
                "msg"=>"error"
            ]);
        }
    }

    //删除操作
    public function destroy(Request $request,$id)
    {
        $user = Branch::find($id);
        $res = $user->delete();
        if($res){
            $data = array(
                "status"=>0,
                "message"=>"删除成功"
            );
        }else{
            $data = array(
                "status"=>1,
                "message"=>"删除失败"
            );
        }
        return $data;
    }

    //批量删除
    public function delAll(Request $request){
        $res = Branch::destroy($request->input('ids'));
        if($res){
            $data = array(
                "status"=>0,
                "message"=>"删除成功"
            );
        }else{
            $data = array(
                "status"=>1,
                "message"=>"删除失败"
            );
        }
        return $data;
    }

    public function curlPost($url,$post_data = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function curlGet($url,$method,$post_data = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8'
            )
        );
        if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        } elseif ($method == 'get') {
            curl_setopt($ch, CURLOPT_HEADER, 0);
        }
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22");
//        curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1");
//        curl_setopt($ch, CURLOPT_PROXYPORT, "2802");
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function getNotice(Request $request){
        $res = $request->all();
        $info['branch'] = htmlspecialchars($res);
        Order::where("id",511)->update($info);
    }

    //定时推送订单
    public function sbOrder(){
        try{
            $order = Order::where("status",'未处理')->first();
            if(isset($order)) {
                $order['remainingnumber'] = $order['remainingnumber'] * $order['num'];
                $res = $this->pushOrder($order['chargeaccount'], $order['orderno'], $order['remainingnumber']*100);
                $res = json_decode($res);
                if($res -> code == 0 || isset($res->msg)){
                    $info['status'] = '已处理';
                    $info['branch'] = '已推送,等待反馈';
                    $info['isok'] = 3;
                    $info['bid'] = 8;
                    Order::where('orderno', $order['orderno'])->update($info);
                    $branch = Branch::where("id",8)->first();
                    $orderInfo['num'] = $branch['num'] + 1;
                    $orderInfo['money'] = $branch['money'] + $order['remainingnumber'];
                    Branch::where("id",$branch['id'])->update($orderInfo);
                }else{
                    $info['branch'] = '推送失败,需和下线确认订单是否充值';
                    $info['status'] = '已处理';
                    $info['isok'] = 2;
                    $info['bid'] = 0;
                    Order::where('orderno', $order['orderno'])->update($info);
                };
            }
            //更新下游的平均完成时间
            echo $order['id'];
            print ("<script type=\"text/javascript\">");
            print ("function fresh_page()");
            print ("{");
            print ("window.location.reload();");
            print ("}");
            print ("setInterval('fresh_page()',3000);");
            print ("</script>");

        }catch (Exception $e){
            echo $e->getMessage();
        }
    }


    //定时确认订单
    public function sbConfirm(){
        try{
            $orders = Order::where("isok",3)->get();
            if(isset($orders)) {
                foreach ($orders as $order){
                    $url = $this->confirmOrder( $order['orderno']);
                    $res = json_decode(file_get_contents($url));
                    if(isset($res -> status)){
                        switch ($res -> status){
                            case 0:
                                $info['branch'] = "待支付";
                                break;
                            case 1:
                                $info['branch'] = "已支付";
                                $info['isok'] = 5;
                                $this->callBackOrderStatus($order['orderno'],1,time());
                                break;
                            case 2:
                                $info['branch'] = "充值失败";
                                $info['isok'] = 2;
                                $this->callBackOrderStatus($order['orderno'],2,time());
                                break;
                        }
                        Order::where('customerorderno', $order['customerorderno'])->update($info);
                    }
                    if( time() - $order['time'] >= 1000){
                        $info['branch'] = "已超时退单";
                        $info['isok'] = 2;
                        $this->callBackOrderStatus($order['orderno'],2,time());
                        Order::where('customerorderno', $order['customerorderno'])->update($info);
                    }
                }
            }
            print ("<script type=\"text/javascript\">");
            print ("function fresh_page()");
            print ("{");
            print ("window.location.reload();");
            print ("}");
            print ("setInterval('fresh_page()',5000);");
            print ("</script>");

        }catch (Exception $e){
            echo $e->getMessage();
        }
    }

    //推送订单
    public function pushOrder($dyid,$orderid,$money){
//        $callbackUrl = "http://120.27.247.117/home/branch/autoConfirmOrder";
        $callbackUrl = "http://112.124.24.221/home/branch/autoConfirmOrder";
        $mchId = 561503;
        $num = rand(1000,9999);
        $data = [
            "amount" => $money,
            "mchId" => $mchId,
            "mchOrderNo" => $orderid,
            "notifyUrl" => $callbackUrl,
            "number" => $dyid,
            "operator" => 7,
            "sign" => strtoupper(md5("amount=".$money."&mchId=".$mchId."&mchOrderNo=".$orderid."&notifyUrl=".$callbackUrl."&number=".$dyid."&operator=7&key=AQPRZOWRR8KEGXRYK5GCFIUEXRBJAT2U0RDBPMCXQTPAVDE2SMFJ0MQRIF5EHRUNZLMPINQ3EYXG0JXB9TWORO4DVQKLI80KTY11OXRAGFKSDET5DC7FYHQN2H7H8CCS"))
        ];
        $url = "http://39.109.112.173:9980/api/open/addSupplyNumber";
        $res = $this->curlGet($url,'post',json_encode($data));
        $info = [
            "ext" => $res
        ];
        Order::where("orderno",$orderid)->update($info);
        $res1 = json_decode($res);
        if($res1 -> code != 0){
//            Mail::raw('订单推送失败,订单编号:'.$orderid, function($message){
//                $message->to('82779539@qq.com');
//                $message->to('171161005@qq.com');
//                $message->to('499841540@qq.com');
//                $message->to('376808741@qq.com');
//                $message->subject('推单失败，联系黎军,手机号:18934642920');
//            });
        }
        return $res;
    }

    //确认订单
    public function confirmOrder($orderid){
        $mchid = 1631866179;
        $userkey = 917661794545150;
        $sign = md5($mchid.$orderid.$userkey);
        $url = "http://155.235.245.38/dyapi.php?mchid=".$mchid."&action=query&orderid=".$orderid."&sign=".$sign;
        $res = $this->curlGet($url,'get');
        return $res;
    }

    //自动推送确认订单isok
    //0订单列表显示已启用，默认
    //1订单完成
    //2订单列表显示已停用，失败反馈给福禄
    //3订单列表显示已推送,等待反馈
    //4失败，但是没反馈给福禄
    //5反馈福禄订单成功
    public function autoConfirmOrder(Request $request){
        $get = $request -> all();
        $status = "error";
        switch ($get['directStatus']){
            case 0:
                $info = ['branch'=>'订单生成'];
                break;
            case 1:
                $info = ['branch'=>'等待充值'];
                break;
            case 2:
                $order = Order::where('orderno',$get['mchOrderNo'])->first();
                $time = time();
                $oktime = $time - strtotime($order['buytime']);
                $info = ['branch'=>'充值失败','isok'=>2,'time'=>$time,'oktime'=>$oktime];
                $this->callBackOrderStatus($get['mchOrderNo'],2,time());
                $status = "error";
                break;
            case 3:
                $order = Order::where('orderno',$get['mchOrderNo'])->first();
                $time = time();
                $oktime = $time - strtotime($order['buytime']);
                $info = ['branch'=>'充值失败，已退款','isok'=>2,'time'=>$time,'oktime'=>$oktime];
                $this->callBackOrderStatus($get['mchOrderNo'],2,time());
                $status = "error";
                break;
            case 4:
                $info = ['branch'=>'充值中'];
                break;
            case 5:
                $order = Order::where('orderno',$get['mchOrderNo'])->first();
                $time = time();
                $oktime = $time - strtotime($order['buytime']);
                $info = ['branch'=>'充值成功','isok'=>1,'time'=>$time,'oktime'=>$oktime];
                $this->callBackOrderStatus($get['mchOrderNo'],1,time());
                $status = "success";
                break;
            default:
                $info = ['branch'=>'超时'];
        }
        Order::where("orderno",$get['mchOrderNo'])->update($info);
        return $status;
    }
}
